<?php
namespace common\components\services\msg;

use common\components\helpers\Fun;
use common\components\helpers\MsgeventData;
use common\models\datas\MsgLog;
use common\models\datas\MsgTemplate;
use yii\base\Component;
use yii\base\Event;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use zhtfrontend\models\datas\ClassStudent;

class MsgEventManage extends Component{
    public $eventArray;

    public $ownerArray;

    public $eventKey;
    const EVENT_SEND_MSG="eventsendmsg";
    /*
     * 获取配置信息，生成出模板内容，其中的动态参数需要更新
     */
    public function afterInsertSend(){
        if(empty($this->eventKey)){
            return;
        }
        $branch_db = Fun::getSiteDb();
        $site_id = Fun::getSiteId();$admin_id=null;
        if(\Yii::$app->request->get('site') != null){
            $admin_id = \Yii::$app->user->id;//分店管理员在操作
        }
        \Yii::$app->queue->push(new SendmsgJob(['eventKey'=>$this->eventKey,'ownerArray'=>$this->ownerArray,'db'=>$branch_db,'site_id'=>$site_id,'admin_id'=>$admin_id]));
        return;
    }

    public function sendTelephoneValidateCode(){
        if(empty($this->eventKey)){
            return;
        }
        $templatearr=$this->getMsgtemplate();
        foreach ($templatearr as $tpl){
            $this->msgtemplateSend($tpl);
        }
    }

    public function event_send_msg($event){
        \Yii::error('event start');
        \Yii::error($event->data);
    }


    private function msgtemplateSend($tpl){
        if($tpl == null){
            return;
        }
        //获取接收者信息
        $mobile_key = $email_key = null;
        $receive_name = $tpl['receive_group'];
        $receive_detail = $this->getReceiveDetail($receive_name);
        $template = $tpl['template'];
        if($receive_detail != null && isset($receive_detail['model']) && !empty($receive_detail['model'])){
            if(isset($receive_detail['mobile_key']) && !empty($receive_detail['mobile_key'])){
                $mobile_key = $receive_detail['mobile_key'];
                //$receive_detail['model'][$receive_detail['mobile_key']];
            }
            if(isset($receive_detail['email_key']) && !empty($receive_detail['email_key'])){
                $email_key = $receive_detail['email_key'];
                //$receive_detail['model'][$receive_detail['mobile_key']];
            }
        }
        if($template['sys_state'] == 1){
            $receive_info = null;
            $tplsys = $this->getMessageTemplatesSys($template);
            $receive_info = $receive_detail['key_related_value']?$receive_detail['key_related_value']:'';
            $send_way = 'sys';
            $this->sendMsglog($send_way,$receive_info,$receive_name,$tplsys);
        }

        if($template['sms_state'] == 1){//当短信发送模板开启
            $receive_info = null;
            $MessageTemplatesms=$this->getMessageTemplateSms($template);
            if(!empty($receive_detail['model'])){
                if(!empty($mobile_key)){
                    $receive_info = $receive_detail['model'][$mobile_key]?$receive_detail['model'][$mobile_key]:'';
                }
            }else{
                $receive_info = $receive_detail['key_related_value'];//直接获取手机号了
            }
            $send_way = 'sms';
            $this->sendMsglog($send_way,$receive_info,$receive_name,$MessageTemplatesms);
        }

        if($template['email_state'] == 1){
            $receive_info = null;
            $Messageemailname=(new MsgeventData())->getNameByKey($this->eventKey);
            $MessageTemplatemail = $this->getMessageTemplateMail($template);
            if(!empty($receive_detail['model'])){
                if(!empty($email_key)){
                    $receive_info = $receive_detail['model'][$email_key]?$receive_detail['model'][$email_key]:'';
                }
            }else{
                $receive_info = $receive_detail['key_related_value'];//直接获取邮件了
            }
            $send_way = 'email';
            $this->sendMsglog($send_way,$receive_info,$receive_name,$MessageTemplatemail,$Messageemailname);
        }

        if($template['wechat_state'] == 1){//微信发送只针对用户，不针对无微信的教师机构，功能需求待定
            $receive_info = null;
            $Messagewechatname=(new MsgeventData())->getNameByKey($this->eventKey);
            $MessageTemplatwechat = $this->getMessageTemplateWechat($template);
            //还不确定存放opendid的表在哪里，暂时就按照login_auth来
            $site = (new Query())->select('web_site_id')->from('{{%site}}')->where(['id'=>Fun::getSiteId()])->one();
            $login_auth = (new Query())->from('{{%login_auth}}')->select('source_id')->where(['user_id'=>$receive_detail['key_related_value']])
                ->andWhere(['web_site_id'=>$site['web_site_id']])->one();//根据关联的用户id值到loginauth中获取对应的openid
            $receive_info = $login_auth['source_id'];
            $send_way = 'wechat';
            $this->sendMsglog($send_way,$receive_info,$receive_name,$MessageTemplatwechat,$Messagewechatname);
        }

    }

    /**
     * @param $receive_name
     * @return null
     * 是独发，不是群发，如果跨了很多歌表则中间会有->来进行链接
     */
    public function getReceiveDetail($receive_name)
    {
        $receive_arr = explode('->',$receive_name);
        $result = null;
        if(!empty($receive_arr)){
                foreach ($receive_arr as $k=>$v){
                    if($k == 0){
                        $first_group = (new MsgeventData())->getReceiveGroupByKey($v);
                        $first_model = isset($first_group['model']) ? $first_group['model'] : null;
                        $related_key = $first_group['key'];//用户在对应的模型中的外键字段名
                        $mobile_key = isset($current_group['mobile_key'])&&!empty($current_group['mobile_key'])?$current_group['mobile_key']:null;
                        $email_key = isset($current_group['email_key'])&&!empty($current_group['email_key'])?$current_group['email_key']:null;
                        $key_related_value = ArrayHelper::keyExists($related_key, $this->ownerArray) ? $this->ownerArray[$related_key] : '';
                        if(!empty($key_related_value)){
                            if(!empty($first_model)){
                                $result = $first_model::findOne($key_related_value);
                            }else{
                                $result = null;
                                break;
                            }
                        }else{
                            $result = null;
                            break;
                        }
                    }else{
                        if(!empty($result)){
                            $current_group = (new MsgeventData())->getReceiveGroupByKey($v);
                            $current_model = $current_group['model'];
                            $current_key = $current_group['key'];
                            $mobile_key = isset($current_group['mobile_key'])&&!empty($current_group['mobile_key'])?$current_group['mobile_key']:null;
                            $email_key = isset($current_group['email_key'])&&!empty($current_group['email_key'])?$current_group['email_key']:null;
                            $key_related_value = $result->hasAttribute($current_key) ? $result->$current_key : '';
                            if(!empty($key_related_value)){
                                $result = $current_model::findOne($key_related_value);
                            }else{
                                $result = null;
                                break;
                            }
                        }
                    }
                }
                if(!empty($result)){
                    $data['key_related_value'] = $key_related_value;//接收系统消息，或者是微信消息需要这个角色的id
                    $data['model'] = $result;
                    $data['mobile_key'] = $mobile_key;//接收短息
                    $data['email_key'] = $email_key;//接收邮件
                    return $data;
                }
        }else{
            return null;
        }
    }

    private function sendMsglog($send_way,$receiver_info,$send_group,$template,$template_name=''){
        if(!empty($receiver_info)){
            $log_id=$this->writeLog($send_way,$this->eventKey,$receiver_info,$send_group,$template,$template_name);
            if(!empty($log_id)){
                $object=\Yii::createObject(['class'=>MsgSendManage::className()]);
                $object->send($log_id);
            }
        }
    }

    /*
     * 要获取个什么样的配置呢？
     * 获取消息的模板和接收的对象的配置信息
     */
    public function getMsgtemplate(){
        $tpl_arr = (new MsgeventData())->getTemplatebyKey($this->eventKey);
        $result_arr = $result_group = $result_single = [];
        if($tpl_arr != '不存在' && count($tpl_arr) > 0){
            foreach ($tpl_arr as $k=>$v){
                if($k !== 'group'){
                    //k是模板code，v是接收的对象信息
                    $mt = MsgTemplate::findOne(['msg_template_code'=>$k]);
                    if($mt){
                        $result['template'] = $mt;
                        $result['receive_group'] = $v;
                        $result_single[] = $result;
                    }else{
                        \Yii::error('msg template is empty');
                    }
                }else{
                    foreach ($v as $h=>$group_item){
                        $mtt = MsgTemplate::findOne(['msg_template_code'=>$h]);
                        if($mtt){
                            $result['template'] = $mtt;
                            $result['receive_group'] = $group_item;
                            $result_group[] = $result;
                        }
                    }
                }
            }
            $result_arr['single'] = $result_single;
            $result_arr['group'] = $result_group;
        }
        return $result_arr;
    }

    //获取系统模板
    private function getMessageTemplatesSys($tpl){
        $str_sys = $tpl['sys_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_sys,'{$'.$k.'}')){
                $str_sys = str_replace('{$' . $k . '}', $v, $str_sys);
            }
        }
        return $str_sys;
    }

    //获取微信模板，如果没有标题设置可以直接用模板名称来作为标题,参考旧项目吧标题废了吧
    private function getMessageTemplateWechat($tpl){
        $str_wechat = $tpl['wechat_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_wechat,'{$'.$k.'}')){
                $str_wechat = str_replace('{$' . $k . '}', $v, $str_wechat);
            }
        }
        return $str_wechat;
    }

    //获取邮件模板
    private function getMessageTemplateMail($tpl){
        $str_email = $tpl['email_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_email,'{$'.$k.'}')){
                $str_email = str_replace('{$' . $k . '}', $v, $str_email);
            }
        }
        return $str_email;
    }

    //获取邮件模板
    private function getMessageTemplateSms($tpl){
        $str_sms = $tpl['sms_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_sms,'{$'.$k.'}')){
                $str_sms = str_replace('{$' . $k . '}', $v, $str_sms);
            }
        }
        return $str_sms;
    }

    //将待发的消息写入到log中
    private function writeLog($send_way,$message_type_id,$receiver_info,$send_group,$message_text,$message_name=''){
        $messageLog = new MsgLog();
        $messageLog->site_id = Fun::getSiteId();
        $messageLog->message_type_id = $message_type_id;
        $messageLog->send_way = $send_way;
        $messageLog->receiver_info = $receiver_info;
        $messageLog->send_group = $send_group;
        $messageLog->message_name = $message_name;
        $messageLog->message_text = $message_text;
        if(\Yii::$app->request->get('site') != null){
            $messageLog->admin_id = \Yii::$app->user->id;//分店管理员在操作
        }
        if($messageLog->save(false)){
            return $messageLog->id;
        }else{
            \Yii::error('write log error');
            return null;
        }
    }

}